package com.doubao.hardware.controller;

import com.doubao.hardware.context.UserContext;
import com.doubao.hardware.dto.ApiResponse;
import com.doubao.hardware.dto.DeviceRegistrationDTO;
import com.doubao.hardware.entity.HardwareDeviceEntity;
import com.doubao.hardware.service.DeviceRegistrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 设备注册控制器
 * 提供设备注册的REST API接口
 */
@RestController
@RequestMapping("/hardware/registration")
@RequiredArgsConstructor
@Slf4j
public class DeviceRegistrationController {

    private final DeviceRegistrationService deviceRegistrationService;

    /**
     * 注册设备
     * @param registrationDTO 设备注册信息
     * @return 注册结果
     */
    @PostMapping
    public ApiResponse<HardwareDeviceEntity> registerDevice(@Valid @RequestBody DeviceRegistrationDTO registrationDTO) {
        try {
            // 如果DTO中没有提供userId，尝试使用当前登录的用户ID
            if (registrationDTO.getUserId() == null && UserContext.isUserLoggedIn()) {
                log.info("从上下文中获取当前用户ID: {}", UserContext.getUserId());
                registrationDTO.setUserId(UserContext.getUserId());
            }

            // 注册设备
            HardwareDeviceEntity device = deviceRegistrationService.registerDevice(registrationDTO);
            return ApiResponse.success("设备注册成功", device);
        } catch (Exception e) {
            log.error("设备注册失败", e);
            return ApiResponse.error("设备注册失败: " + e.getMessage());
        }
    }

    /**
     * 检查设备是否已注册
     * @param macAddress 设备MAC地址
     * @return 检查结果
     */
    @GetMapping("/check/{macAddress}")
    public ApiResponse<Boolean> checkDeviceRegistered(@PathVariable String macAddress) {
        boolean isRegistered = deviceRegistrationService.isDeviceRegistered(macAddress);
        return ApiResponse.success(isRegistered);
    }

    /**
     * 绑定设备到用户
     * @param deviceId 设备ID
     * @param userId 用户ID
     * @return 绑定结果
     */
    @PostMapping("/{deviceId}/bind/{userId}")
    public ApiResponse<Void> bindDeviceToUser(@PathVariable Long deviceId, @PathVariable Long userId) {
        try {
            // 检查是否有权限绑定设备
            if (!UserContext.isUserLoggedIn()) {
                return ApiResponse.error(401, "请先登录");
            }

            deviceRegistrationService.bindDeviceToUser(deviceId, userId);
            return ApiResponse.success("设备绑定成功", null);
        } catch (Exception e) {
            log.error("设备绑定失败", e);
            return ApiResponse.error("设备绑定失败: " + e.getMessage());
        }
    }

    /**
     * 解绑设备
     * @param deviceId 设备ID
     * @return 解绑结果
     */
    @PostMapping("/{deviceId}/unbind")
    public ApiResponse<Void> unbindDevice(@PathVariable Long deviceId) {
        try {
            // 检查是否有权限解绑设备
            if (!UserContext.isUserLoggedIn()) {
                return ApiResponse.error(401, "请先登录");
            }

            deviceRegistrationService.unbindDevice(deviceId);
            return ApiResponse.success("设备解绑成功", null);
        } catch (Exception e) {
            log.error("设备解绑失败", e);
            return ApiResponse.error("设备解绑失败: " + e.getMessage());
        }
    }

    /**
     * 更新设备在线状态
     * @param deviceId 设备ID
     * @param isOnline 是否在线
     * @return 更新结果
     */
    @PutMapping("/{deviceId}/online")
    public ApiResponse<Void> updateDeviceOnlineStatus(@PathVariable Long deviceId, @RequestParam Boolean isOnline) {
        try {
            deviceRegistrationService.updateDeviceOnlineStatus(deviceId, isOnline);
            return ApiResponse.success("设备在线状态更新成功", null);
        } catch (Exception e) {
            log.error("更新设备在线状态失败", e);
            return ApiResponse.error("更新设备在线状态失败: " + e.getMessage());
        }
    }
}